package com.guli.gulimallproduct.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimallproduct.product.dao.CategoryDao;
import com.guli.gulimallproduct.product.entity.CategoryEntity;
import com.guli.gulimallproduct.product.service.CategoryService;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> selectListAll() {
        QueryWrapper queryWrapper=new QueryWrapper<CategoryEntity>();
        queryWrapper.eq("show_status",1);
        List<CategoryEntity> categoryEntityList= baseMapper.selectList(queryWrapper);
        return categoryEntityList.stream().filter(i->i.getParentCid()==0).map(i->{
            i.setChildrens(getChildrens(i,categoryEntityList));
            return i;
        }).sorted(Comparator.comparingInt(x -> (x.getSort() == null ? 0 : x.getSort()))).collect(Collectors.toList());
    }

    @Override
    public int updateNoShowBatch(List<Long> catIds) {
        return categoryDao.updateNoShowBatch(catIds);
    }

    public static List<CategoryEntity> getChildrens(CategoryEntity parent,List<CategoryEntity> categoryEntityList){
        return categoryEntityList.stream().filter(i->i.getParentCid()==parent.getCatId()).map(i->{
             i.setChildrens(getChildrens(i,categoryEntityList));
             return i;
        }).sorted(Comparator.comparingInt(x -> (x.getSort() == null ? 0 : x.getSort()))).collect(Collectors.toList());
    }
}